/*
 * @Author: WangShuai 1830773767@qq.com
 * @Date: 2025-06-23 14:32:42
 * @LastEditors: WangShuai 1830773767@qq.com
 * @LastEditTime: 2025-06-24 19:51:39
 * @FilePath: \shangyitong\src\store\modules\user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
//定义用户和登录相关的仓库
import { defineStore } from "pinia";
import { reqUserCode } from '@/api/hospital/index'
import { reqUserLogin, reqUserLogout } from '@/api/user/index'
import type { LoginData, UserLoginResponse, } from '@/api/user/type'
import type { UserState } from './type/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/user";
const useUserStore = defineStore("User", {
    state: (): UserState => {
        return {
            visible: false, //用于控制登录组件对话框dialog的显示和隐藏
            smsCode: "",//验证码
            userInfo: JSON.parse(GET_TOKEN() as string) || {}
        }
    },
    actions: {
        //获取验证码方法
        async getUerCode(phoneNum: string) {
            //在向服务器携带手机号码,获取验证码
            //正常开发的时候,只需要发一个请求,后台就会将验证码发送到用户手机设备中
            //目前项目服务器不能向用户手机设备发送验证码,因此用接口的方式返回
            let result = await reqUserCode(phoneNum)
            if (result.code == 200) {
                this.smsCode = result.data
                return "ok"
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        //用户登录方法
        async userLogin(data: LoginData) {
            let result: UserLoginResponse = await reqUserLogin(data)
            if (result.code == 200) {
                this.userInfo = result.data
                //持久化保存用户信息
                SET_TOKEN(JSON.stringify(this.userInfo))
                //返回一个成功的Primise
                return "ok"
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        //退出登录方法
        async userLogout() {
            //清空用户信息
            REMOVE_TOKEN()
            this.smsCode = "";
            this.userInfo = {
                name: "",
                token: "",
            }
        },
        //查询微信打码的接口.查询本地是否 存储 用户数据
        queryState() {
            //开启定时器 每隔一段时间查询本地存储是否拥有用户信息
            let timer = setInterval(() => {
                //说明本地存储已有数据:扫码成功
                if (GET_TOKEN()) {
                    //关闭对话框
                    this.visible = false;
                    this.userInfo = JSON.parse(GET_TOKEN() as string)
                    clearInterval(timer)
                }
            }, 1000)
        }
    },
    getters: {

    },
    // 启用持久化配置
    persist: true,
})

export default useUserStore